from django.shortcuts import render
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

from .forms import  WechatVerifyForm
from .models import WechatVerify
import os,json

def _get_env_name(request):
    url_path = request.path
    return url_path.split('/')[3]

@csrf_exempt
def files_view(request):

    env_name = _get_env_name(request)
    form = WechatVerifyForm()
    if request.method == 'GET':
        return render(request , 'wechatverifyupload/templates/verify.html',{'form':form})

    elif request.method == 'POST':
        datas = WechatVerify.objects.all()
        newdatas = []
        for data in datas:
            print(data.env.website)
            newdatas.append({'id':data.id,
                             'env':data.env.name,
                             'file':data.file.name,
                             'desc':data.desc,
                             'go':'<a href="{url}">{name}</a>'.format(
                                 url=os.path.join(data.env.website,data.file.name),
                                name=data.file.name)})
        return HttpResponse(json.dumps(newdatas))


@csrf_exempt
def upload_file(request):
    if request.method =="GET":
        form = WechatVerifyForm()

        return render(request , 'wechatverifyupload/templates/add.html')
    if request.method == 'POST':
        form = WechatVerifyForm(request.POST,request.FILES)
        form.save()
        print(request.POST)
        print(request.FILES)
        if form.is_valid():
            wechatverify = WechatVerify()
            wechatverify.env = form.cleaned_data["env"]
            wechatverify.file = form.cleaned_data["file"]
            wechatverify.desc = form.cleaned_data["desc"]
            form.save()
            return HttpResponse(json.dumps({'code':10000,'msg':"OK"}))

        print(form.errors)